import {
  Get,
  Controller,
  Body,
  Post,
  Param,
  Query,
  Res,
  Header,
} from '@nestjs/common';
import type { Response } from 'express';
import { GisService } from './gis.service';
import { GisGetInfoDto } from './dto/gis-modal';
import { initThreadId, responseText } from './utils/common';
import data from './db/data.json';

@Controller('gis')
export class GisController {
  constructor(private readonly gisService: GisService) {}

  @Get('/')
  hello() {
    return 'this is gis';
  }
  @Get('/data')
  getData() {
    return { code: 200, data };
  }

  @Post('/chat/message')
  async chatMessage(@Body() body: GisGetInfoDto, @Res() res: Response) {
    const { messagesList, modelConfig } = body;
    const chatSessionId = body.chatSessionId || 'gis-session-' + initThreadId();

    const result = await this.gisService.chatMessage({
      chatSessionId,
      messagesList,
      modelConfig,
    });

    // 根据返回结果类型处理响应
    if (result instanceof ReadableStream) {
      // 流式响应
      res.writeHead(200, { 'Content-Type': 'text/event-stream' });

      // 将流式数据写入响应
      const reader = result.getReader();

      const pump = async () => {
        while (true) {
          const { done, value } = await reader.read();
          if (done) {
            res.end();
            break;
          }
          res.write(value);
        }
      };

      await pump();
    } else {
      // 非流式响应
      res.json({ data: result });
    }
  }
  @Post('/chat/message/gen')
  async chatMessageGen(@Body() body: GisGetInfoDto, @Res() res: Response) {
    console.log('body>>111', JSON.stringify(body, null, 2));
    const { messagesList, modelConfig } = body;
    const chatSessionId = body.chatSessionId || 'gis-session-' + initThreadId();

    const result = await this.gisService.chatMessageGen({
      chatSessionId,
      messagesList,
      modelConfig,
    });
    if (modelConfig?.streaming) {
      res.setHeader('Content-Type', 'text/event-stream');
      while (true) {
        const { value, done } = await result.next();
        if (done) {
          res.write(responseText({ type: 'end', chatSessionId }));
          res.end();
          break;
        }
        res.write(responseText({ type: 'chunk', content: value.content }));
      }

      return;
    }
    while (true) {
      const { value, done } = await result.next();
      if (done) {
        res.end();
        break;
      }
      res.json({ data: value });
    }
  }

  // 获取对话历史
  @Get('/chat/history/:sessionId')
  getChatHistory(@Param('sessionId') sessionId: string) {
    return this.gisService.getChatHistory(sessionId);
  }

  // 清除对话历史
  @Post('/chat/clear/:sessionId')
  clearChatHistory(@Param('sessionId') sessionId: string) {
    return this.gisService.clearChatHistory(sessionId);
  }
}
